import dayjs from 'dayjs'
/* 封装全局 工具方法 */
wx.utils = {
  message(title, icon = "none") {
    wx.showToast({
      title,
      icon,
      duration: 1000,
      mask: true
    })
  },
  upload(filePath, formData) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${wx.baseURL}/upload`,
        filePath,
        name: 'file',
        formData,
        header: {
          Authorization: getApp().state.token
        },
        success: (result) => {
          const res = JSON.parse(result.data)
          // setTimeout(() => {
          //   wx.utils.message(res.message)
          // }, 1000);
          if (res.code === 1e4) {
            resolve(res)
          } else {
            // 上传失败
            // 处理 token 过期
            if (res.code === 401) {
              // 读取当前历史栈
              const pageStack = getCurrentPages()
              // 取出当前页面路径，登录成功能跳转到该页面
              const currentPage = pageStack[pageStack.length - 1]
              wx.redirectTo({
                url: `/pages/login/index?redirectUrl=/${currentPage.route}`
              })
            }
            reject(res)
          }
        }
      });
    })
  },
  formatTime(date, type = 'YYYY-MM-DD') {
    return dayjs(date).format(type)
  }
}